package com.crm.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.BearerTokenCredentials;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.mysql.fabric.xmlrpc.base.Data;

/**
 * 在crm系统中有时候可能会经常用到的util工具
 * */

public class CrmUtil {
	
	
	/**
	 * 将证书类型id转换城中文
	 * */
	public static String getNameByTypesId(int typesId){
		String name = null;
		if (typesId == 3) {
			name = "不限";
		} else if (typesId == 1) {
			name = "初始";
		} else {
			name = "转注册";
		}
		return name;
	}
	
	/**
	 * 将证书用途id转换成中文
	 * */
	public static String getNameByPaperspurposeId(int paperspurposeId){
		String name = null;
		if (paperspurposeId == 1) {
			name = "升资质";
		} else if (paperspurposeId == 2) {
			name = "挂项目";
		} else if (paperspurposeId == 3) {
			name = "动态核查";
		} else {
			name = "其他";
		}
		return name;
	}
	
	/**
	 * 判断两个String类型的时间之间的差值是否小于规定的差值<br>
	 * 传入三个参数,开始时间,结束时间,差值<br>
	 * 用<b>开始时间</b>减去<b>结束时间</b>,再与设定的差值比较
	 * 获取一个boolean类型的结果<br>
	 * @param
	 * 	starttime (String)(yyyy-MM-dd)开始时间
	 * @param
	 * 	endtime (String)(yyyy-MM-dd)结束时间
	 * @param
	 * 	difference (Long)设定的差值
	 * @return
	 * 	 boolean 如果在差值之内,返回true,否则返回false
	 * */
	public static boolean checkTimeDifference(String starttime,String endtime,Long difference){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Long startdate = 0L;
		Long enddate = 0L;
		try {
			//将String类型的时间转换成Long类型的毫秒数
			startdate = sdf.parse(starttime).getTime();
			enddate = sdf.parse(endtime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//将毫秒转换成天数转换
		Long day = (startdate-enddate)/1000/60/60/24;
		if (day < difference) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 判断开始时间是否在结束时间之前(也就是有没有过期)
	 * 开始时间等于结束时间的情况会判定为没过期
	 * @param
	 * 	starttime (String)(yyyy-MM-dd)开始时间
	 * @param
	 * 	endtime (String)(yyyy-MM-dd)结束时间
	 * @return
	 * 	 boolean 如果没过期,返回true,如果过期了,返回false
	 * */
	public static boolean checkIsPastDue(String starttime,String endtime){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Long startdate = 0L;
		Long enddate = 0L;
		try {
			//将日期转换成毫秒
			startdate = sdf.parse(starttime).getTime();
			enddate = sdf.parse(endtime).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//对日期进行判断(随着日期的增长,毫秒数是不断变大的)
		if (startdate >= enddate) {
			return true;
		} else {
			return false;
		}
	}
	
	
	public static void main(String[] args) {
		
		
	}
	
	
	   /**
     * 生产环境的Region是cn-shanghai
     */
    private static final String REGION = "cn-shanghai";
    private static final String PRODUCT = "CCC";
    private static final String ENDPOINT = "CCC";
    /**
     * 生产环境的Region是ccc.cn-shanghai.aliyuncs.com
     */
    private static final String DOMAIN = "ccc.cn-shanghai.aliyuncs.com";
    
    private static final String VERSION = "2017-07-05";
 
    public static  String invokeApiByBearerToken(String accessToken, String action, String request) throws ClientException {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put(PRODUCT, DOMAIN);

        DefaultProfile profileBear = DefaultProfile.getProfile(REGION);
        profileBear.addEndpoint(ENDPOINT, REGION, PRODUCT, DOMAIN);

        BearerTokenCredentials bearerTokenCredentials =
                new BearerTokenCredentials(accessToken);
        DefaultAcsClient accessTokenClient = new DefaultAcsClient(profileBear, bearerTokenCredentials);
        accessTokenClient.setAutoRetry(false);

        /**
         * 使用CommonAPI调用POP API时，和使用传统产品SDK相比，请求和返回参数的格式都有所不同，因此需要进行一定的格式转换。
         */
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setDomain(DOMAIN);
        commonRequest.setVersion(VERSION);
        commonRequest.setAction(action);
        JSONObject jsonObject = JSONObject.parseObject(request);

        for (Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey().trim();
            if (key.length() > 1) {
                key = key.substring(0, 1).toUpperCase() + key.substring(1);
            } else if (key.length() == 1) {
                key = key.toUpperCase();
            } else {
                continue;
            }
            commonRequest.putQueryParameter(key, entry.getValue().toString());
        }

        commonRequest.putQueryParameter("accessToken", accessToken);
        CommonResponse response = null;
        try {
            response = accessTokenClient.getCommonResponse(commonRequest);
          //  System.out.println(JSONObject.toJSONString(response.getData()));
        } catch (ClientException e) {
           // logger.error("Failed to invoke open API, request=" + JSON.toJSONString(commonRequest), e);
        //    throw new Exception(e.getRequestId(), e.getErrCode(), e.getMessage());
        }

        JSONObject jsonResult = JSONObject.parseObject(response.getData());
        JSONObject newJsonResult = new JSONObject();
        copyObject(newJsonResult, jsonResult);
        return JSONObject.toJSONString(newJsonResult);
    }
 
    
    public static  String invokeApiByBearerTokenClient(String accessToken, String action, String request) throws ClientException {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put(PRODUCT, DOMAIN);

        DefaultProfile profileBear = DefaultProfile.getProfile(REGION);
        profileBear.addEndpoint(ENDPOINT, REGION, PRODUCT, DOMAIN);

        BearerTokenCredentials bearerTokenCredentials =
                new BearerTokenCredentials(accessToken);
        DefaultAcsClient accessTokenClient = new DefaultAcsClient(profileBear, bearerTokenCredentials);
        accessTokenClient.setAutoRetry(false);

        /**
         * 使用CommonAPI调用POP API时，和使用传统产品SDK相比，请求和返回参数的格式都有所不同，因此需要进行一定的格式转换。
         */
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setDomain(DOMAIN);
        commonRequest.setVersion(VERSION);
        commonRequest.setAction(action);
        JSONObject jsonObject = JSONObject.parseObject(request);

        for (Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey().trim();
            if (key.length() > 1) {
                key = key.substring(0, 1).toUpperCase() + key.substring(1);
            } else if (key.length() == 1) {
                key = key.toUpperCase();
            } else {
                continue;
            }
            commonRequest.putQueryParameter(key, entry.getValue().toString());
        }

        commonRequest.putQueryParameter("accessToken", accessToken);
        CommonResponse response = null;
        try {
            response = accessTokenClient.getCommonResponse(commonRequest);
       
          //  System.out.println(JSONObject.toJSONString(response.getData()));
        } catch (ClientException e) {
           // logger.error("Failed to invoke open API, request=" + JSON.toJSONString(commonRequest), e);
        //    throw new Exception(e.getRequestId(), e.getErrCode(), e.getMessage());
        }
 
        return response.getData();
    }
 

    private static void copyArray(JSONArray destination, JSONArray source) {
        Iterator<Object> iterator = source.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof JSONObject) {
                JSONObject newObject = new JSONObject();
                destination.add(newObject);
                copyObject(newObject, (JSONObject) object);
            } else if (object instanceof JSONArray) {
                JSONArray newArray = new JSONArray();
                destination.add(newArray);
                copyArray(newArray, (JSONArray) object);
            } else {
                destination.add(object);
            }
        }
    }
 
   private static void copyObject(JSONObject destination, JSONObject source) {
        for (Entry<String, Object> entry : source.entrySet()) {
            String key = entry.getKey().trim();
            if (key.length() > 1) {
                key = key.substring(0, 1).toLowerCase() + key.substring(1);
            } else if (key.length() == 1) {
                key = key.toUpperCase();
            } else {
                continue;
            }

            Object object = entry.getValue();

            if (object instanceof JSONObject) {
                JSONObject tempObject = (JSONObject) object;
                if (tempObject.entrySet().size() == 1) {
                    Object theOne = tempObject.entrySet().iterator().next().getValue();
                    if (theOne instanceof JSONArray) {
                        JSONArray newArray = new JSONArray();
                        destination.put(key, newArray);
                        copyArray(newArray, (JSONArray) theOne);
                        continue;
                    }
                }
                JSONObject newObject = new JSONObject();
                destination.put(key, newObject);
                copyObject(newObject, (JSONObject) object);
            } else if (object instanceof JSONArray) {
                JSONArray newArray = new JSONArray();
                destination.put(key, newArray);
                copyArray(newArray, (JSONArray) object);
            } else {
                destination.put(key, object);
            }
        }
    }
	
	
	

}
